package cn.zk.commom.tcp.obd;

import org.springframework.stereotype.Component;

import java.util.ArrayList;

//货车数据项
@Component
public class PositionItemTruckData {
    public final int  mOilType;   //剩余油量单位类型，0：百分比% 1：单位L -1：无效数据（mRemainingOil、mOilType无效）
    public final double  mRemainingOil;   //剩余油量

    public PositionItemTruckData(byte[] data) {
        ArrayList<byte[]> infos = DataSplitting(data);
        if(infos.size() == 0) {
            mOilType = -1;
            mRemainingOil = 0.0;
            return;
        }

        int oilType = -1;
        double remainingOil = 0.0;
        for(int i = 0; i < infos.size(); ++i)
        {
            byte[] var = infos.get(i);
            int type = (int)ByteArrayToLong(var, 0, 2);
            int len = var[2];

            byte[] sub_data = new byte[len];
            System.arraycopy(var, 3, sub_data, 0, sub_data.length);

            switch (type) {
                case 0x62f0: //剩余油量
                    //
                    if (len == 2) {
                        long tep1 = (int)ByteArrayToLong(sub_data, 0, 2);
                        oilType = (int) ((tep1 & 0X00008000) >> 15);
                        remainingOil = (tep1 & 0X00007FFF) / 10.0;
                    }
                    break;
                default: break;
            }
        }

        mOilType = oilType;
        mRemainingOil = remainingOil;
    }

    /***
     * 拆分扩展信息的数据
     * @param data 位置信息数据
     * @return 返回经过拆分处理的数据
     */
    private ArrayList<byte[]> DataSplitting(byte[] data) {
        ArrayList<byte[]> ret = new ArrayList<>();

        int sub_index = 0;
        while(true)
        {
            if(sub_index + 3 > data.length )
                break;

            //0-1:子类型; 2:子类型长度
            int sub_len  = (int)ByteArrayToLong(data, sub_index + 2, 1);   //子类型长度
            int new_index = sub_index + sub_len + 3;

            if(new_index > data.length)
                break;

            byte[] _tep = new byte[sub_len + 3];
            System.arraycopy(data, sub_index, _tep, 0, _tep.length);
            ret.add(_tep);

            sub_index = new_index;
        }

        return  ret;
    }

    private static long ByteArrayToLong(byte[] data, int index ,int len) {
        if(index < 0 || len <= 0 || index >= data.length || len + index > data.length)
            return  0;

        //
        long ret = (data[index] & 0xff);
        for(int i = 1; i < len; ++i)
        {
            ret = (ret << 8)  + (data[i + index] & 0xff);
        }

        return  ret;
    }

}
